package com.ww.learn.actors

import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.SendChannel
import kotlinx.coroutines.channels.actor
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

// 订单分配相关消息
sealed class OrderMessage {
    data class AllocateOrder(val orderId: String): OrderMessage() // 分配订单
    data class AllocateResult(val orderId: String, val success: Boolean): OrderMessage() // 分配结果
}

// 库存检查消息（跨服务Actor通信）
data class CheckInventory(val orderId: String, val response: CompletableDeferred<Boolean>)

// 订单分配Actor
//fun CoroutineScope.orderDispatcherActor(
//    inventoryActor: SendChannel<CheckInventory>, // 库存服务Actor
//    paymentActor: SendChannel<CheckPayment>, // 支付服务Actor
//    deliveryActor: SendChannel<AssignDelivery> // 配送服务Actor
//): SendChannel<OrderMessage> = actor<OrderMessage> {
//    for (msg in channel) {
//        when (msg) {
//            is OrderMessage.AllocateOrder -> {
//                var success = false
//                try {
//                    // 1.检查库存
//                    val inventoryOk = CompletableDeferred<Boolean>()
//                    inventoryActor.send(CheckInventory(msg.orderId, inventoryOk))
//                    if (!inventoryOk.await()) {
//                        log.warn("订单${msg.orderId}库存不足")
//                        return@try
//                    }
//
//                    // 2.检查支付状态
//                    val paymentOk = CompletableDeferred<Boolean>()
//                    paymentActor.send(CheckPayment(msg.orderId, paymentOk))
//                    success = deliveryOk.await()
//                } finally {
//                    // 发送分配结果（用于后续重试或通知）
//                    send(OrderMessage.AllocateResult(msg.orderId, success))
//                    // 失败则加入重试队列（简化逻辑，实际可加延迟重试）
//                    if (!success) {
//                        launch {
//                            delay(5000) // 5秒后重试
//                            send(OrderMessage.AllocateOrder(msg.orderId))
//                        }
//                    }
//                }
//            }
//            is OrderMessage.AllocateResult -> {
//                orderDao.updateStatus(msg.orderId, if (msg.success) "ALLOCATED" else "ALLOCATE_FAILED")
//            }
//        }
//    }
//}